import React, { useEffect, useMemo } from 'react';
import { StyleSheet, View } from 'react-native';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withSequence,
  withTiming,
  withSpring,
  runOnJS,
  interpolate,
  Easing,
} from 'react-native-reanimated';
import { FontAwesome } from '@expo/vector-icons';

type Props = {
  startX: number;
  startY: number;
  endX: number;
  endY: number;
  onComplete: () => void;
};

const FloatingHeart = ({ startX, startY, endX, endY, onComplete }: Props) => {
  const progress = useSharedValue(0);
  const scale = useSharedValue(1);
  const opacity = useSharedValue(1);

  // 使用 useMemo 缓存控制点计算
  const controlPoints = useMemo(() => ({
    x: (startX + endX) / 2 - 50,
    y: Math.min(startY, endY) - 100,
  }), [startX, endX, startY, endY]);

  useEffect(() => {
    const duration = 800;

    progress.value = withTiming(1, {
      duration,
      easing: Easing.bezier(0.4, 0, 0.2, 1),
    }, () => {
      runOnJS(onComplete)();
    });

    scale.value = withTiming(0.7, {
      duration,
      easing: Easing.bezier(0.4, 0, 0.2, 1),
    });

    opacity.value = withSequence(
      withTiming(1, { duration: duration * 0.7 }),
      withTiming(0, { duration: duration * 0.3 })
    );
  }, [startX, startY, endX, endY, onComplete]);

  const animatedStyle = useAnimatedStyle(() => {
    const t = progress.value;
    
    // 贝塞尔曲线计算
    const x = (1 - t) * (1 - t) * startX + 2 * (1 - t) * t * controlPoints.x + t * t * endX;
    const y = (1 - t) * (1 - t) * startY + 2 * (1 - t) * t * controlPoints.y + t * t * endY;

    return {
      transform: [
        { translateX: x - startX },
        { translateY: y - startY },
        { scale: scale.value },
      ],
      opacity: opacity.value,
    };
  });

  return (
    <Animated.View 
      style={[
        styles.heart, 
        { left: startX - 12, top: startY - 12 },
        animatedStyle,
      ]}
    >
      <FontAwesome 
        name="heart" 
        size={24}
        color="#ff4d4f" 
      />
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  heart: {
    position: 'absolute',
    width: 24,
    height: 24,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default FloatingHeart; 